﻿
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace WPFDemoMVVM.Behaviors
{
    public class SelectedItemBehavior: Behavior<FrameworkElement>
    {
        #region SelectedItem DependencyProperty

        public object SelectedItem {
            get => GetValue(SelectedItemProperty);
            set => SetValue(SelectedItemProperty, value);
        }
        public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
            nameof(SelectedItem), typeof(object), typeof(SelectedItemBehavior),new PropertyMetadata(null,OnSelectedItemChanged));

        private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = Interaction.GetBehaviors(d).OfType<SelectedItemBehavior>().FirstOrDefault();
            if (behavior == null) { return; }
            foreach (var child in behavior!.Children)
            {
                child.IsChecked = child.Tag.Equals(e.NewValue);
            }
        }

        #endregion


        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (_, _) =>
            {
                foreach (var child in Children)
                {
                    child.Checked += OnRadioButtonChecked;
                    child.IsChecked = child.Tag.Equals(SelectedItem);
                }
            };            
        }

        private void OnRadioButtonChecked(object sender, RoutedEventArgs e)
        {
            var radio = sender as RadioButton;
            SelectedItem = radio!.Tag;
            BindingOperations.GetBindingExpression(this, SelectedItemProperty).UpdateSource();
        }

        private IEnumerable<RadioButton> Children
        {
            get
            {
                if(AssociatedObject is Panel panel)
                    return panel.Children.OfType<RadioButton>();
                else if(AssociatedObject is ItemsControl control)
                    return control.Items.OfType<RadioButton>();
                return Enumerable.Empty<RadioButton>();
            }
        }

    }
}
